package com.apes.framework.plugin.esb.processor.connector.proxy;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.esb.processor.AbstractChainProcessor;
import com.apes.oap.RopRequestContext;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.Map;

/**
 * 功能：Http代理
 *
 * @author xul
 * @create 2019-10-22 17:29
 */
public class HttpProxyProcessor<T extends SimpleRequest, R> extends AbstractChainProcessor<T, R> {

    @Override
    public R process(T data) {
        Object result = super.process(data);
        if (result instanceof Map) result = JSONObject.toJSONString(result);
        if (!(result instanceof String)) throw new RuntimeException("HttpProxy输入数据格式不正确。");
        RopRequestContext context = data.getRopRequestContext();
        HttpServletResponse response = (HttpServletResponse) context.getRawResponseObject();
        if(response == null)  throw new RuntimeException("Http代理请求失败,response为空！");
        response.setContentType("application/json;charset=utf-8");

        try (OutputStream os = response.getOutputStream()) {
            os.write(((String) result).getBytes());
            os.flush();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return (R) result;
    }

    @Override
    protected R doProcess(T data) {
        return (R) data.getData();
    }

}
